package com.ext.aic.utils.device;

import android.content.Context;
import android.text.TextUtils;

import com.ext.aic.beans.DeviceMeta;
import com.eyinfo.android_pure_utils.encryption.Md5Utils;
import com.eyinfo.android_pure_utils.utils.GlobalUtils;
import com.eyinfo.android_pure_utils.utils.JsonUtils;
import com.eyinfo.mpkv.MPLocalKV;

public class DeviceUtils {
    private static volatile DeviceUtils instance;

    public static DeviceUtils getInstance() {
        if (instance == null) {
            synchronized (DeviceUtils.class) {
                if (instance == null) {
                    instance = new DeviceUtils();
                }
            }
        }
        return instance;
    }

    private DeviceMeta deviceInfo;
    private String deviceId;

    public DeviceMeta getDeviceInfo(Context context) {
        if (deviceInfo != null && !TextUtils.isEmpty(deviceInfo.getId()) && !EmulatorJudge.hasInvalidIds(deviceInfo.getId())) {
            return deviceInfo;
        }
        String deviceCacheKey = "dae4f968732cd5bd";
        String deviceJson = MPLocalKV.getInstance().getString(deviceCacheKey, "{}");
        deviceInfo = JsonUtils.fromJson(deviceJson, DeviceMeta.class);
        if (deviceInfo != null && !TextUtils.isEmpty(deviceInfo.getId())) {
            return deviceInfo;
        }
        DeviceHelper deviceHelper = new DeviceHelper();
        DeviceMeta response = deviceHelper.getSysDeviceInfo(context);
        response.setSimulator(EmulatorJudge.isEmulator(context));
        response.setRoot(RootJudge.isRoot());
        String json = JsonUtils.toJson(response);
        MPLocalKV.getInstance().put(deviceCacheKey, json);
        deviceInfo = response;
        return response;
    }

    public String getDeviceId(Context context) {
        if (!TextUtils.isEmpty(deviceId)) {
            return deviceId;
        }
        DeviceHelper deviceHelper = new DeviceHelper();
        String deviceUnique = deviceHelper.generateDeviceUnique(context);
        if (!TextUtils.isEmpty(deviceUnique)) {
            deviceId = deviceUnique;
        } else {
            String androidId = deviceHelper.getAndroidId(context);
            if (!TextUtils.isEmpty(androidId)) {
                deviceId = androidId;
            } else {
                //这种情况理论上是不可能出现的,为了逻辑的完整性这里还是加上
                deviceId = String.format("0x1%s", Md5Utils.encryptForHex(GlobalUtils.getNewGuid()));
            }
        }
        return deviceId;
    }
}
